﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace Informant.UI.Wpf.Utilities
{
	public static class TextBoxHelper
	{
		#region UpdateBindingOnTextChanged DependencyProperty

		// Using a DependencyProperty as the backing store for UpdateBindingOnTextChanged.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty UpdateBindingOnTextChangedProperty =
			DependencyProperty.RegisterAttached("UpdateBindingOnTextChanged",
				typeof(Boolean),
				typeof(TextBoxHelper),
				new PropertyMetadata(false, UpdateBindingOnTextChanged));
		
		public static void SetUpdateBindingOnTextChanged(DependencyObject dp, Boolean value)
		{
			dp.SetValue(UpdateBindingOnTextChangedProperty, value);
		}
		public static Boolean GetUpdateBindingOnTextChanged(DependencyObject dp)
		{
			return (Boolean)dp.GetValue(UpdateBindingOnTextChangedProperty);
		}

		/// <summary>
		/// Attaches or detaches a TextChangedHandler to the dp if it's a TextBox.
		/// </summary>
		/// <param name="dp">The dp.</param>
		/// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
		private static void UpdateBindingOnTextChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
		{
			TextBox textBox = dp as TextBox;
			if (textBox != null)
			{
				// Detach the old TextChangedHanlder if one was attached last
				//	time this property was changed to prevent memory leaks.
				if ((Boolean)e.OldValue)
				{
					textBox.TextChanged -= TextChangedHanlder;
				}
				// Attach a new TextChangedHandler if desired.
				if ((Boolean)e.NewValue)
				{
					textBox.TextChanged += TextChangedHanlder;
				}
			}
		}
		/// <summary>
		/// Handles the TextChanged event of a TextBox.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="e">The <see cref="System.Windows.Controls.TextChangedEventArgs"/> instance containing the event data.</param>
		private static void TextChangedHanlder(Object sender, TextChangedEventArgs e)
		{
			// Based on http://betaforums.silverlight.net/forums/t/103695.aspx
			TextBox textBox = (TextBox)sender;
			if (textBox != null)
			{
				BindingExpression bindingExpression = textBox.GetBindingExpression(TextBox.TextProperty);
				if (bindingExpression != null)
				{
					bindingExpression.UpdateSource();
				}
			}
		}

		#endregion
	}
}
